package com.ljd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljd.client.VodClient;
import com.ljd.entity.EduVideo;
import com.ljd.mapper.EduVideoMapper;
import com.ljd.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.util.R;
import com.why.handler.GuliException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.geom.QuadCurve2D;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author ljd
 * @since 2021-12-10
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    VodClient vodClient;

    @Override
    public void saveVideo(EduVideo video) {
        baseMapper.insert(video);
    }

    @Override
    public void updateVideo(EduVideo video) {
        UpdateWrapper<EduVideo> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", video.getId());
        baseMapper.update(video,wrapper);
    }

    @Override
    public Boolean deleteVideo(String videoId) {
        EduVideo video = baseMapper.selectById(videoId);
        String videoVideoSourceId = video.getVideoSourceId();
        if(StringUtils.isEmpty(videoVideoSourceId)){
            throw new GuliException(20001,"小节未添加视频，无法移除视频");
        }
        // 删除小节和视频
        R r = vodClient.deleteAlyVideo(videoVideoSourceId);
        if(r.getCode() == 20001){
            throw new GuliException(20001,"删除视频失败");
        }
        int i = baseMapper.deleteById(videoId);
        return i>0;
    }

    @Override
    public EduVideo getVideo(String videoId) {
        EduVideo video = baseMapper.selectById(videoId);
        if(video == null){
            return new EduVideo();
        }
        return video;
    }

    // 批量删除小节和视频
    @Override
    public void removeBatch(String courseId) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        List<EduVideo> eduVideos = baseMapper.selectList(queryWrapper);

        List<String> videoSourceIds = eduVideos.stream().map(EduVideo::getVideoSourceId).filter(sourceId -> !StringUtils.isEmpty(sourceId)).distinct().collect(Collectors.toList());

        if(videoSourceIds.size()>0){
            vodClient.deleteBatch(videoSourceIds);
        }

       baseMapper.delete(queryWrapper);

    }
}
